/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月22日
 */
package com.massyframework.beanskin.launching.web;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.framework.Framework;
import com.massyframework.beanskin.framework.FrameworkConfig;
import com.massyframework.beanskin.framework.FrameworkFactory;
import com.massyframework.beanskin.launcher.DefalutLauncher;
import com.massyframework.beanskin.launching.Launcher;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionCollectUtils;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionGroup;


/**
 * 提供在Servlet 3.1以上容器中自动加载Massy Framework的能力
 * 
 * @author huangkh
 *
 */
public class WebApplicationInitializer implements ServletContainerInitializer {

	private Logger logger = LoggerFactory.getLogger(WebApplicationInitializer.class);
	
	/**
	 * 构造方法
	 */
	public WebApplicationInitializer() {
	}

	@Override
	public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {	
		Map<String, String> configuration = new HashMap<>();
        configuration.put(Framework.RUN_ENVIRONMENT, Framework.RUN_ENVIRONMENT_J2EE);
                		
        try {
        	ExceptionGroup group = new ExceptionGroup();
	        ExceptionCollectUtils.bind(group);
	        
        	Launcher launcher = new WebLauncher(new J2eeEnvironmentSetter(ctx));
	        Framework framework = launcher.launch();
	       
	        framework.init(); 
	        ctx.setAttribute(Framework.class.getName(), framework);
	        ctx.addListener(new FrameworkStartStopListener());
        }catch(Exception e) {
        	if (logger.isErrorEnabled()) {
    			logger.error(e.getMessage(), e);
    		}
        }
	}

	private class WebLauncher extends DefalutLauncher {
		
		private Consumer<FrameworkConfig> action;
		
		public WebLauncher (Consumer<FrameworkConfig> action) {
			this.action = action;
		}
		
		@Override
		protected Framework createFramework(FrameworkConfig config, FrameworkFactory factory) {
			if (action != null) {
				action.accept(config);
			}
			return super.createFramework(config, factory);
		}
				
	}
}
